package com.ikas.autumn.iec104.common.baseEntity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.ikas.autumn.iec104.common.enums.GlobalConstants;
import com.ikas.autumn.iec104.common.enums.JsonResultConstants;
import com.ikas.autumn.iec104.common.handle.JsonSerializeHandler;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 返回给前台的json结果
 *
 * @author HXH
 */
public class JsonResult extends LinkedHashMap{

    public final static String TAGCODE = "code";
    public final static String TAGMSG = "msg";
    public final static String TAGDATA = "data";
    public final static String TAGURL = "url";
    public final static String TAGREMARK = "remark";
    /**
     * 处理空值
     */
    private final ValueFilter filter = (obj, s, v) -> v == null ? "" : v;
    private int type ;
    private static String message = "";
    private static String remark = "";

    /**
     * 构造函数
     */
    public JsonResult() {
        this.type = JsonResultConstants.OK;
        this.put(TAGCODE, this.getType());
        this.put(TAGMSG, this.getMessage());
        this.put(TAGREMARK,this.getRemark());
    }

    /**
     * 构造函数
     *
     * @param type 结果类型
     */
    public JsonResult(int type) {
        this();
        this.setType(type);
    }

    public JsonResult(int type, String message) {
        this(type);
        this.setMessage(message);
    }

    /**
     * 正常返回的无参静态方法
     */
    public static JsonResult ok() {
        return new JsonResult(JsonResultConstants.OK);
    }

    /**
     * 正常返回的有值静态方法
     */
    public static <T> JsonResult ok(T result) {
        JsonResult json = ok();
        json.add(result);
        return json;
    }

    /**
     * 无参异常返回
     *
     * @return
     */
    public static JsonResult error() {
        return error(JsonResultConstants.ERROR);
    }

    /**
     * 带参异常返回
     * @param type
     * @return
     */
    public static JsonResult error(int type) {
        return error(type,message);
    }

    /**
     * 异常返回错误信息
     *
     * @return
     */
    public static JsonResult error(String message) {
        return error(JsonResultConstants.ERROR, message);
    }

    /**
     * 带参异常返回
     * @param type
     * @return
     */
    public static JsonResult error(int type, String message) {
        return new JsonResult(type,message);
    }


    /**
     * 正常返回的无参静态方法
     */
    public static String success() {
        JsonResult json = ok();
        return json.toJSON();
    }

    /**
     * 正常返回的有值静态方法
     * @param result 返回对象
     */
    public static <T> String success(T result) {
        JsonResult json = ok();
        json.add(result);
        return json.toJSON();
    }
    /**
     * 正常返回的有值静态方法
     * @param message 返回信息
     */
    public static <T> String success(String message) {
        JsonResult json = ok();
        json.setMessage(message);
        return json.toJSON();
    }

    /**
     * 失败返回的无参静态方法
     */
    public static String fail() {
        JsonResult json = error();
        return json.toJSON();
    }
    /**
     * 失败返回的无参静态方法
     */
    public static String fail(String msg) {
        JsonResult json = error(msg);
        return json.toJSON();
    }

    /**
     * 增加传出的结果
     *
     * @param key
     * @param value
     * @return
     */
    public JsonResult add(String key, Object value) {
        if (this.containsKey(key)) {
            this.remove(key);
        }
        boolean bsuccess = false;
        if (value instanceof String) {
            String tmp = value.toString();
            if (isJsonObject(tmp)) {
                JSONObject obj = JSON.parseObject(tmp, Feature.OrderedField);
                this.put(key, obj);
                bsuccess = true;
            } else if (isJsonArray(tmp)) {
                JSONArray obj = JSON.parseArray(tmp);
                this.put(key, obj);
                bsuccess = true;
            }
        }
        if (!bsuccess) {
            this.put(key, value);
        }
        return this;
    }

    /**
     * 增加集合到集合中
     *
     * @param data
     * @param total
     * @return
     */
    public JsonResult add(List<?> data, int total) {
        this.add(TAGDATA, data);
        this.add("iTotalRecords", total);
        this.add("iTotalDisplayRecords", total);
        return this;
    }

    /**
     * 增加单个数据对象到集合中
     *
     * @param data
     * @return
     */
    public JsonResult add(Object data) {
        this.add(TAGDATA, data);
        return this;
    }

    /**
     * 移除传出的结果
     *
     * @param key
     * @return
     */
    public JsonResult remove(String key) {
        this.remove(key);
        return this;
    }

    /**
     * 输出JSON字符串
     *
     * @return
     */
    public String toJSON() {
        return JSONObject.toJSONString(toJsonObject(), JsonSerializeHandler.instance(), filter, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.SortField, SerializerFeature.MapSortField);
    }

    /**
     * 输出JSON对象（FastJSON）
     * @return
     */
    public Object toJsonObject() {
        this.put(TAGCODE, type);
        if (type == JsonResultConstants.SESSIONTIMEOUT) {
            this.put(TAGURL, GlobalConstants.URL_LOGIN);
        }
        this.put(TAGMSG, this.getMessage());
        if (StringUtils.isNotBlank(this.getRemark())) {
            this.put(TAGREMARK, this.getRemark());
        }
        return JSONObject.toJSON(this, JsonSerializeHandler.instance());
    }

    /**
     * 输出参数列表
     *
     * @return
     */
    public Map<String, Object> getResult() {
        this.put(TAGCODE, this.getType());
        return this;
    }


    /**
     * 获得结果类型
     *
     * @return
     */
    public int getType() {
        return type;
    }

    /**
     * 设置结果类型
     *
     * @param type
     * @return
     */
    public JsonResult setType(int type) {
        this.type = type;
        return this;
    }

    /**
     * 返回消息
     *
     * @return
     */
    public String getMessage() {
        return message;
    }

    /**
     * 设置返回的消息
     *
     * @param message
     * @return
     */
    public JsonResult setMessage(String message) {
        JsonResult.message = message;
        return this;
    }

    /**
     * 获取备注信息
     *
     * @return
     */
    public String getRemark() {
        return remark;
    }

    /**
     * 设置返回备注信息
     *
     * @param remark
     * @return
     */
    public JsonResult setRemark(String remark) {
        JsonResult.remark = remark;
        return this;
    }

    /**
     * 判断字符串是否是json对象
     * @param string
     * @return
     */
    private boolean isJsonObject(String string) {
        try {
            Object object = JSON.parse(string);
            if(object instanceof JSONObject) {
                return true;
            }else{
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 判断字符串是否是json集合对象
     * @param string
     * @return
     */
    private boolean isJsonArray(String string) {
        try {
            Object object = JSON.parse(string);
            if(object instanceof JSONArray) {
                return true;
            }else{
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

}
